/**
 * MongoDB 数据库连接管理模块
 */

const mongoose = require('mongoose');
const dbConfig = require('./config');

class DatabaseConnection {
    constructor() {
        this.connection = null;
        this.isConnected = false;
    }

    /**
     * 连接到 MongoDB 数据库
     * @returns {Promise<mongoose.Connection>} 数据库连接实例
     */
    async connect() {
        if (this.isConnected && this.connection) {
            console.log('📊 已存在数据库连接，复用中...');
            return this.connection;
        }

        try {
            console.log('📊 正在连接到 MongoDB...');
            console.log(`   URI: ${dbConfig.mongodb.uri.replace(/\/\/.*@/, '//***@')}`); // 隐藏密码
            
            await mongoose.connect(dbConfig.mongodb.uri, dbConfig.mongodb.options);
            
            this.connection = mongoose.connection;
            this.isConnected = true;
            
            // 监听连接事件
            this.connection.on('connected', () => {
                console.log('✅ MongoDB 连接成功');
            });
            
            this.connection.on('error', (err) => {
                console.error('❌ MongoDB 连接错误:', err.message);
                this.isConnected = false;
            });
            
            this.connection.on('disconnected', () => {
                console.log('⚠️  MongoDB 连接已断开');
                this.isConnected = false;
            });
            
            return this.connection;
            
        } catch (error) {
            console.error('❌ MongoDB 连接失败:', error.message);
            this.isConnected = false;
            throw error;
        }
    }

    /**
     * 断开数据库连接
     */
    async disconnect() {
        if (!this.isConnected || !this.connection) {
            return;
        }

        try {
            await mongoose.connection.close();
            this.isConnected = false;
            this.connection = null;
            console.log('✅ MongoDB 连接已关闭');
        } catch (error) {
            console.error('❌ 关闭 MongoDB 连接失败:', error.message);
            throw error;
        }
    }

    /**
     * 检查连接状态
     * @returns {boolean} 是否已连接
     */
    isConnectionActive() {
        return this.isConnected && mongoose.connection.readyState === 1;
    }

    /**
     * 获取连接实例
     * @returns {mongoose.Connection} 连接实例
     */
    getConnection() {
        return this.connection;
    }
}

// 导出单例
module.exports = new DatabaseConnection();

